/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Utils;

/**
 *
 * @author user
 */
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import org.gjt.mm.mysql.*;

public class DBConnection {

    String DBName, DBUser, DBPass, SQLQuery;
    public Connection conn;
    Statement stmt;
    ResultSet result;

    public DBConnection(String DBName, String DBUser, String DBPass) {
        try {
            this.DBName = DBName;
            this.DBUser = DBUser;
            this.DBPass = DBPass;

            Class.forName("org.gjt.mm.mysql.Driver");
            connect();
        } catch (Exception e) {
        }
    }

    public void connect() {
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost/" + DBName + "?user=" + DBUser + "&password=" + DBPass);
        } catch (Exception e) {
        }
    }

    public ResultSet ExecuteQuery(String SQLQuery) {
        try {
            stmt = conn.createStatement();
            result = stmt.executeQuery(SQLQuery);
        } catch (Exception e) {
        }
        return result;
    }

    public int ExecuteUpdate(String SQLQuery) {
        int rows = 0;
        try {
            stmt = conn.createStatement();
            rows = stmt.executeUpdate(SQLQuery);
        } catch (Exception e) {
            throw new Exception(e);
        } finally {
            return rows;
        }
    }

    public int ExecuteInsert(String SQLQuery) {
         int id=-1;
        try {
            stmt = conn.createStatement();
            int res = stmt.executeUpdate(SQLQuery);
            ResultSet rs = stmt.getGeneratedKeys();
            if (rs.next()) {
                id = rs.getInt(1);
            }
        } catch (Exception e) {
            throw new Exception(e);
        } finally {
            return id;
        }
    }

    public void close() {
        try {
            stmt.close();
            conn.close();
        } catch (Exception e) {
        }
    }
}
